package net.qhzw.vip.qiyu.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import ma.glasnost.orika.MapperFacade;
import net.qhzw.vip.qiyu.dto.CategoryDto;
import net.qhzw.vip.qiyu.entity.Category;
import net.qhzw.vip.qiyu.mapper.CategoryBrandMapper;
import net.qhzw.vip.qiyu.mapper.CategoryMapper;
import net.qhzw.vip.qiyu.mapper.CategoryPropMapper;
import net.qhzw.vip.qiyu.service.AttachFileService;
import net.qhzw.vip.qiyu.service.CategoryService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    @Autowired
    private CategoryPropMapper categoryPropMapper;

    @Autowired
    private AttachFileService attachFileService;

    @Autowired
    private MapperFacade mapperFacade;

    @Override
    public List<Category> listByParentId(Long parentId) {
        return categoryMapper.listByParentId(parentId);
    }

    @Override
    public List<Category> tableCategory(Long shopId) {
        return categoryMapper.tableCategory(shopId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveCategroy(Category category) {
        category.setRecTime(new Date());
        // 保存分类信息
        categoryMapper.insert(category);

        insertBrandsAndAttributes(category);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCategroy(Category category) {
        Category dbCategory = categoryMapper.selectById(category.getCategoryId());
        category.setUpdateTime(new Date());
        // 保存分类信息
        categoryMapper.updateById(category);
        // 先删除后增加
        deleteBrandsAndAttributes(category.getCategoryId());
        insertBrandsAndAttributes(category);
        // 如果以前有图片，并且图片与现在不同，则删除以前的图片
//		if (StrUtil.isNotBlank(dbCategory.getPic()) && !dbCategory.getPic().equals(category.getPic())) {
//			attachFileService.deleteFile(dbCategory.getPic());
//		}
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCategroy(Long categoryId) {
        Category category = categoryMapper.selectById(categoryId);
        categoryMapper.deleteById(categoryId);

        deleteBrandsAndAttributes(categoryId);
//		if (StrUtil.isNotBlank(category.getPic())) {
//			attachFileService.deleteFile(category.getPic());
//		}
    }


    private void deleteBrandsAndAttributes(Long categoryId) {
        // 删除所有分类所关联的品牌
        categoryBrandMapper.deleteByCategoryId(categoryId);
        // 删除所有分类所关联的参数
        categoryPropMapper.deleteByCategoryId(categoryId);
    }

    private void insertBrandsAndAttributes(Category category) {
        //保存分类与品牌信息
        if (CollUtil.isNotEmpty(category.getBrandIds())) {
            categoryBrandMapper.insertCategoryBrand(category.getCategoryId(), category.getBrandIds());
        }

        //保存分类与参数信息
        if (CollUtil.isNotEmpty(category.getAttributeIds())) {
            categoryPropMapper.insertCategoryProp(category.getCategoryId(), category.getAttributeIds());
        }
    }

    @Override
    public List<Category> treeSelect(int grade) {
        List<Category> categories = categoryMapper.selectList(new LambdaQueryWrapper<Category>()
                .le(Category::getGrade, grade));
        return categoryListToTree(categories);
    }

    public List<Category> categoryListToTree(List<Category> categorys) {
        if (org.apache.commons.collections.CollectionUtils.isEmpty(categorys)) {
            return Lists.newArrayList();
        }
        Map<Long, List<Category>> categoryMap = categorys.stream().collect(Collectors.groupingBy(Category::getParentId));

        List<Category> rootList = categoryMap.get(0L);
        transformCategoryTree(rootList, categoryMap);
        return rootList;
    }

    public void transformCategoryTree(List<Category> categorys, Map<Long, List<Category>> categoryMap) {
        for (Category category : categorys) {
            List<Category> nextList = categoryMap.get(category.getCategoryId());
            if (CollectionUtils.isEmpty(nextList)) {
                continue;
            }
            // 将排序完成的list设为下一层级
            category.setCategories(nextList);
            // 处理下 下一层级
            transformCategoryTree(nextList, categoryMap);
        }
    }

    @Override
    public List<CategoryDto> listCategoryDtoByShopId(Long shopId) {
        List<Category> categoryList = categoryMapper.listCategoryAndProdByShopId(shopId);
        return mapperFacade.mapAsList(categoryList, CategoryDto.class);
    }


//    /***
//     * 查询全部类目
//     * @param id
//     * @return
//     */
//    @Override
//    public List<MallCategory> findAll() {
//        List<MallCategory> list = list(new LambdaQueryWrapper<MallCategory>()
//                .last("order by sort, created desc"));
//        if (CollectionUtils.isEmpty(list)) {
//            return Collections.emptyList();
//        }
//        //一级类目
//        List<MallCategory> rootCategory = list.stream().filter(mallCategory ->
//                mallCategory.getParentId() == null || mallCategory.getParentId() == 0)
//                .collect(Collectors.toList());
//        //查询所以的子类目
//        for (MallCategory category : rootCategory) {
//            category.setChilds(getChildCategorys(category.getId(), list));
//        }
//        return rootCategory;
//    }
//
//    private List<MallCategory> getChildCategorys(Long parentId, List<MallCategory> sources) {
//        List<MallCategory> childs = new ArrayList<>();
//        for (MallCategory source : sources) {
//            if (source.getParentId().equals(parentId)) { // 找儿子
//                childs.add(source);
//                source.setChilds(getChildCategorys(source.getId(), sources)); // 给该儿子设置儿子
//            }
//        }
//        return childs;
//    }


}
